﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Ganosoft.DynamicProxy;
using Ganosoft.Aspect;

namespace GanoESB.Component
{
    public class ExecutingInvocation : IServiceInvocation
    {
        private object target;
        private ServiceDescriptor descr;
        private InvocationInfo invocation;
        private IServiceInterceptor[] interceptors;
        private int index;

        public ExecutingInvocation(object target, ServiceDescriptor descr, InvocationInfo invocation)
        {
            this.target = target;
            this.descr = descr;
            this.invocation = invocation;
            this.interceptors = AspectContainer.Instance.GetInterceptors(descr.ServiceClazz, invocation.TargetMethod.Name);
        }

        #region IServiceInvocation 成员

        public ServiceCall ServiceCall
        {
            get { return null; }
        }

        public object InvokeNext()
        {
            if (interceptors != null && interceptors.Length > 0)
                if (index < interceptors.Length)
                    return interceptors[index++].Invoke(this);
            
            return invocation.TargetMethod.Invoke(target, invocation.Arguments);
        }

        public Type TargetType
        {
            get { return invocation.Target.GetType(); }
        }

        public MethodInfo Method
        {
            get { return invocation.TargetMethod; }
        }

        public object[] Args
        {
            get { return invocation.Arguments; }
        }

        #endregion
    }
}
